package bo.zhao.action.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Student implements Cloneable, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5115181874920873337L;

	private String name = null;
	private Integer age = null;

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	private List<Book> books = new ArrayList<>();

	public void addBook(String name, Integer pages) {
		Book book = new Book();
		book.setName(name);
		book.setPages(pages);
		books.add(book);
	}

	/**
	 * 浅复制：将一个对象复制后，基本数据类型的变量都会重新创建，而引用类型，指向的还是原对象所指向的。
	 */
	public Student normalClone() {
		try {
			return (Student) super.clone();
		} catch (CloneNotSupportedException e) {
			return null;
		}
	}

	public Student deepClone() {
		try {
			
			/* 写入当前对象的二进制流 */
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(this);

			/* 读出二进制流产生的新对象 */
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bis);
			return (Student) ois.readObject();
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public String toString() {
		StringBuffer builder=new StringBuffer();
		builder.append("Student("+this.hashCode()+");"+super.toString()+"\n");
		for (Book book : books) {
			builder.append("\t"+book.toString()+"\n");
		}
		return builder.toString();
	}

}
